import request from "@/app/(dashboard)/common/request";
import { MyAxiosRequestConfig } from "@/lib/util/axios";
import { useEffect, useState } from "react";
interface UseRequestConfig<D> extends MyAxiosRequestConfig {
    /**请求路径 */
    url: string,
    /**请求数据 */
    data: D,
    /**请求方法 - 有需要可以扩展 */
    method: 'get' | 'post'
}
/**请求hook，在页面挂载时请求，自带loading状态和错误状态，同时返回函数支持二次调用
 * - 暂时未使用，但是不能没有
 * @param config axios配置项
 * @param initVal 数据的初始值
 * @returns [data, loading, err, getData]
 */
export default function useRequest<T, D>(config: UseRequestConfig<D>, initVal: T) {
    const [data, setData] = useState<T>(initVal)
    const [err, setErr] = useState()
    const [loading, setLoading] = useState(false)
    const getData = async () => {
        try {
            const { data, url, method, ...axiosConfig } = config
            let res: T
            setLoading(true)
            switch (method) {
                case 'get':
                    res = await request.get<T, D>(url, data, axiosConfig)
                    break;
                case 'post':
                    res = await request.post<T, D>(url, data, axiosConfig)
                    break;
                default:
                    throw 'method错误'
            }
            setData(res)
        } catch (error: any) {
            setErr(error)
        } finally {
            setLoading(false)
        }
    }
    useEffect(() => {
        getData()
    }, [])
    return [data, loading, err, getData] as [T, boolean, any, () => Promise<void>]
}